package com.buddha.api.controller;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.map.MapUtil;
import com.buddha.api.common.Constants;
import com.buddha.api.common.Result;
import com.buddha.api.entity.User;
import com.buddha.api.service.impl.UserServiceImpl;
import com.buddha.api.utils.RedisUtil;
import com.google.code.kaptcha.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.Principal;
import java.util.Base64;



@CrossOrigin(origins = {"*"})
@RestController
public class CaptchaController {
    @Autowired
    private Producer producer;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    UserServiceImpl userService;

    /*--------------获取验证码-------------*/
    @GetMapping(value = "/captcha")
    public Result captcha(){
        String key = UUID.randomUUID().toString();
        String code = producer.createText();
        System.out.println(key);
        key="aaa";
        code="111";
        BufferedImage image = producer.createImage(code);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            ImageIO.write(image,"jpg", outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }

        Base64.Encoder encoder = Base64.getEncoder();
        String str = "data:image/jpeg;base64,";
        String base64Img = str + encoder.encodeToString(outputStream.toByteArray());
        redisUtil.hset(Constants.CAPTCHA_KEY,key,code,120);
        return Result.success(MapUtil.builder()
                .put("token",key)
                .put("captImg",base64Img)
                .build()
        );
    }

    @GetMapping("/sys/userInfo")
    public Result userInfo(Principal principal){
        User user = userService.findByUsername(principal.getName());
        return Result.success(MapUtil.builder()
                .put("id", user.getId())
                .put("username", user.getUsername())
                .put("avatar", user.getAvatar())
                .map());
    }
}

